<template>
  <div class="map-wrapper">
    <!-- 顶部左侧悬浮下拉栏组 -->
    <div class="map-header-left">
      <!-- 切换校区 -->
      <el-dropdown @command="handleCampus">
        <el-button type="primary">
          切换区域
          <el-icon class="ml-1"><ArrowDown /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="center">北苑区域</el-dropdown-item>
            <el-dropdown-item command="west">图书馆区域</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 元素开关下拉复选框 -->
      <el-dropdown>
        <el-button type="primary">
          元素开关
          <el-icon class="ml-1"><ArrowDown /></el-icon>
        </el-button>
        <template #dropdown>
          <!-- 自定义下拉内容：复选框组 -->
          <div class="dropdown-checkbox">
            <el-checkbox-group v-model="checkedElements">
              <el-checkbox
                  v-for="item in elementOptions"
                  :key="item.value"
                  :label="item.value"
              >
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </template>
      </el-dropdown>
    </div>

    <!-- 顶部右侧悬浮栏组 -->
    <div class="map-header-right">
      <el-button @click="handlePrint" type="primary">打印</el-button>
    </div>

    <!-- 地图容器 -->
    <div class="map-container" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted, watch } from 'vue';
import { ArrowDown } from '@element-plus/icons-vue';
import { listElement, getElement, delElement, addElement, updateElement } from "@/api/water/element.js";
import {markersInit, polygonsInit} from '@/api/water/map.js';
import ElementPic from '@/assets/icons/svg/system_green.svg';
import {listArea} from "@/api/water/area.js";
import {ElMessage} from "element-plus";

let map = null;
let elements = [];
const mapContainer = ref(null);
const areaVisible = ref(false);
const loading = ref(true);
let polygons = [];

// 切换校区逻辑
const handleCampus = (command) => {
  console.log('切换校区：', command);
  if (command === 'center') {
    map.centerAndZoom(new BMapGL.Point(114.168202,30.524314), 18); // 北苑区域中心坐标
  } else if (command === 'west') {
    map.centerAndZoom(new BMapGL.Point(114.167382,30.519973), 18); // 图书馆区域中心坐标
  }
};

//元素开关逻辑
// 1. 定义元素配置
const elementOptions = ref([
  { label: '水表', value: 'element' },
  { label: '区域', value: 'area' },
  { label: '标签', value: 'label' },
]);
//绑定复选框选中状态（初始全选）
const checkedElements = ref(['element', 'area', 'label']);
//监听复选框变化，控制地图元素
watch(checkedElements, (newVal) => {
  elementOptions.value.forEach(item => {
    console.log(`${item.label} 显示：`, newVal.includes(item.value));
    if (item.value=='element') {
      newVal.includes(item.value) ? elements.forEach(marker => {map.addOverlay(marker)}) : elements.forEach(marker => {map.removeOverlay(marker)});
    } else if (item.value=='area'){
      newVal.includes(item.value) ? polygons.forEach(polygon => {map.addOverlay(polygon)}) : polygons.forEach(polygon => {map.removeOverlay(polygon)});
    }
  });
});

//打印逻辑
const handlePrint = () => {
  window.print()
}

onMounted(async () => {
  // 初始化百度地图
  map = new BMapGL.Map(mapContainer.value, {minZoom: 16, maxZoom: 20});
  map.centerAndZoom(new BMapGL.Point(114.167382,30.519973), 18);
  map.enableScrollWheelZoom(true);
  map.enableKeyboard(true);
  map.addControl(new BMapGL.ScaleControl());
  map.addControl(new BMapGL.ZoomControl());

  //水表数据初始化
  try {
    loading.value = true;
    const elementList = await listElement({pageSize:10000});
    if (elementList.code === 200 && elementList.rows) {
      elements = markersInit(map, elementList.rows, ElementPic);
      elements.forEach(marker => {map.addOverlay(marker);});
    }
  }catch(error) {
    console.error('获取水表数据时发生错误',error);
    ElMessage.error('获取水表数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }

  try {
    loading.value = true;
    const areaList = await listArea({pageSize: 10000});
    if (areaList.code === 200 && areaList.rows) {
      polygons=polygonsInit(map,areaList.rows);
      polygons.forEach(polygon => {map.addOverlay(polygon);});
    }
  }catch(error) {
    console.error('获取区域数据时发生错误',error);
    ElMessage.error('获取区域数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }

});

onUnmounted(() => {
  if (map) {
    map.clearOverlays();
    map = null;
  }
});
</script>

<style scoped>
.map-wrapper {
  width: 100%;
  height: calc(100vh - 84px);
  position: relative;
}

/* 顶部左侧悬浮栏样式 */
.map-header-left {
  position: absolute;        /* 绝对定位，其位置为相对于wrapper的位置 */
  top: 1%;              /* 距离顶部间距 */
  left: 1%;
  z-index: 1000;          /* 确保在地图上方 */
  display: flex;
  align-items: center;
  gap: 15px;              /* 按钮间距 */
}

/* 下拉复选框的布局 */
.dropdown-checkbox {
  padding: 12px; /* 内边距 */
}
.el-checkbox {
  display: block; /* 每个复选框占一行 */
  margin: 6px 0;  /* 上下间距 */
}

/* 顶部右侧悬浮栏样式 */
.map-header-right {
  position: absolute;        /* 绝对定位，其位置为相对于wrapper的位置 */
  top: 1%;              /* 距离顶部间距 */
  right: 4%;
  z-index: 1000;          /* 确保在地图上方 */
  display: flex;
  align-items: center;
  gap: 15px;              /* 按钮间距 */
}

.map-container {
  width: 100%;
  height: 100%;           /* 填充父容器高度 */
  font-family: "微软雅黑";
}
</style>